package pers.twf.twfRpc.protocol;

import io.vertx.core.buffer.Buffer;
import pers.twf.twfRpc.serializer.Serializer;
import pers.twf.twfRpc.serializer.SerializerFactory;

import java.io.IOException;

/**
 * 消息编码器
 */
public class ProtocolMessageEncoder {

    /**
     * 编码
     * @return
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        if (protocolMessage==null || protocolMessage.getHeader() ==null) {
            return Buffer.buffer();
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

//        获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumBySerializer(header.getSerializer());
        if (serializerEnum==null) {
            throw new RuntimeException("serializer not exist");
        }
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getName());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
//        写入body 长度和数据
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        return buffer;
    }
}
